/**
 *    Copyright (C) 2008, 2009  Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */

#ifndef _CUBEFS_API_EXCEPTIONS_CAST_HPP
#define	_CUBEFS_API_EXCEPTIONS_CAST_HPP

#include <cubefs/api/exceptions/cubefs.hpp>
#include <cubefs/api/reflection/type.hpp>
#include <cubefs/api/exceptions/npe.hpp>

#include <string>

#define CUBEFS_SOURCE "cast.hpp:" CUBEFS_AT

namespace cubefs    {
namespace api       {

using namespace std;

class CUBEFS_API TypeCastException: public CubefsException {
    const Type* src_type_;
    const Type* tgt_type_;

public:
    TypeCastException(const string &source, const string &message, const Type* src_type, const Type* tgt_type):
                CubefsException(source, message), src_type_(src_type), tgt_type_(tgt_type) {}

    TypeCastException(const string &source, const Type* src_type, const Type* tgt_type):
                CubefsException(source, "Invalid type cast"), src_type_(src_type), tgt_type_(tgt_type) {}

    const Type* src_type() const {
        return src_type_;
    }

    const Type* tgt_type() const {
        return tgt_type_;
    }
};

template <typename T>
T* TypedCast(Typed *typed, bool check_null = true) {
    if (check_null && typed == NULL) {
        throw NullPointerException(CUBEFS_SOURCE, "Argument must not be null");
    }

    if (typed != NULL) {
        if (!typed->IsInstance(T::MyType())) {
            throw TypeCastException(CUBEFS_SOURCE, "Can't cast "+typed->type()->name()+" to "+T::MyType()->name(), typed->type(), T::MyType());
        }
        else {
            return static_cast<T*>(typed);
        }
    }
    else {
        return NULL;
    }
}


}
}

#undef CUBEFS_SOURCE

#endif
